package com.sws.web.controller.ry_rongyue.wx;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sws.common.core.domain.AjaxResult;
import com.sws.wx_msg_push.dto.ReservationTemplateDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信消息控制器
 */
@RestController
@RequestMapping("/wx-message")
@Slf4j
public class WxMessageController {

    @Autowired
    @Qualifier("reservationRestTemplate")
    private RestTemplate restTemplate;
    
    @Autowired
    @Qualifier("reservationObjectMapper")
    private ObjectMapper objectMapper;
    
    @Value("${wx.api.base-url:https://api.weixin.qq.com}")
    private String wxApiBaseUrl;
    
    @Value("${wx.api.send-template-url:/cgi-bin/message/template/send}")
    private String sendTemplateUrl;
    
    @Value("${wx.access-token:}")
    private String accessToken;
    
    @Value("${wx.appid:}")
    private String appid;
    
    @Value("${wx.secret:}")
    private String secret;
    
    /**
     * 发送微信模板消息
     * 
     * @param templateMsg 模板消息
     * @return 发送结果
     */
    @PostMapping("/send")
    public AjaxResult sendTemplateMessage(@RequestBody ReservationTemplateDTO templateMsg) {
        try {
            // 记录请求内容
            log.info("接收到模板消息发送请求: {}", objectMapper.writeValueAsString(templateMsg));
            
            // 构建完整的URL，包括access_token参数
            String fullUrl = wxApiBaseUrl + sendTemplateUrl;
            if (accessToken != null && !accessToken.isEmpty()) {
                fullUrl += "?access_token=" + accessToken;
            } else {
                log.warn("微信访问令牌为空，可能导致API调用失败");
            }
            
            log.info("转发模板消息到微信API: {}", fullUrl);
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            // 发送请求
            HttpEntity<ReservationTemplateDTO> requestEntity = new HttpEntity<>(templateMsg, headers);
            ResponseEntity<Map> response = restTemplate.postForEntity(fullUrl, requestEntity, Map.class);
            
            // 解析响应
            Map<String, Object> responseBody = response.getBody();
            log.info("微信API响应: {}", responseBody);
            
            if (responseBody != null) {
                Integer errcode = (Integer) responseBody.get("errcode");
                if (errcode != null && errcode == 0) {
                    return AjaxResult.success("模板消息发送成功");
                } else {
                    String errmsg = (String) responseBody.get("errmsg");
                    return AjaxResult.error("模板消息发送失败: " + errmsg);
                }
            } else {
                return AjaxResult.error("模板消息发送失败: 无响应数据");
            }
            
        } catch (Exception e) {
            log.error("模板消息发送异常", e);
            return AjaxResult.error("模板消息发送异常: " + e.getMessage());
        }
    }
    
    /**
     * 获取微信访问令牌
     * 
     * @return 访问令牌信息
     */
    @PostMapping("/token/refresh")
    public AjaxResult refreshAccessToken() {
        try {
            // 构建获取access_token的URL
            String tokenUrl = wxApiBaseUrl + "/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret;
            
            log.info("请求刷新微信访问令牌: {}", tokenUrl);
            
            // 发送请求
            ResponseEntity<Map> response = restTemplate.getForEntity(tokenUrl, Map.class);
            Map<String, Object> responseBody = response.getBody();
            
            if (responseBody != null && responseBody.containsKey("access_token")) {
                String newToken = (String) responseBody.get("access_token");
                Integer expiresIn = (Integer) responseBody.get("expires_in");
                
                // 这里可以添加保存token的逻辑
                
                Map<String, Object> result = new HashMap<>();
                result.put("access_token", newToken);
                result.put("expires_in", expiresIn);
                
                return AjaxResult.success("访问令牌刷新成功", result);
            } else {
                String errmsg = responseBody != null ? (String) responseBody.get("errmsg") : "未知错误";
                return AjaxResult.error("访问令牌刷新失败: " + errmsg);
            }
            
        } catch (Exception e) {
            log.error("刷新访问令牌异常", e);
            return AjaxResult.error("刷新访问令牌异常: " + e.getMessage());
        }
    }

    /**
     * 测试微信访问令牌
     * 
     * @return 测试结果
     */
    @PostMapping("/token/test")
    public AjaxResult testAccessToken() {
        try {
            // 构建测试access_token的URL
            String testUrl = wxApiBaseUrl + "/cgi-bin/getcallbackip?access_token=" + accessToken;
            
            log.info("测试微信访问令牌: {}", testUrl);
            
            // 发送请求
            ResponseEntity<Map> response = restTemplate.getForEntity(testUrl, Map.class);
            Map<String, Object> responseBody = response.getBody();
            
            if (responseBody != null && responseBody.containsKey("ip_list")) {
                return AjaxResult.success("访问令牌有效", responseBody);
            } else {
                Integer errcode = responseBody != null ? (Integer) responseBody.get("errcode") : null;
                String errmsg = responseBody != null ? (String) responseBody.get("errmsg") : "未知错误";
                
                if (errcode != null && errcode == 40001) {
                    return AjaxResult.error("访问令牌无效或已过期: " + errmsg);
                } else {
                    return AjaxResult.error("测试访问令牌失败: " + errmsg);
                }
            }
            
        } catch (Exception e) {
            log.error("测试访问令牌异常", e);
            return AjaxResult.error("测试访问令牌异常: " + e.getMessage());
        }
    }
} 